<script setup>
import { ArchiveOutline as ArchiveIcon } from "@vicons/ionicons5";
import Header from "@/components/header/Header.vue";
import { useRoute } from "vue-router";
import { requestHomeWorkDetail, requestSubmitHomework } from "@/api/home-work/homeWorkApi";
import { useSpinStore } from '@/store/spin'
// 引入进度条插件
import editor from "@/components/editor/Editor.vue";
import { requestUploadHomework, getUpToken } from "@/api/oss/ossApi";
import * as qiniu from 'qiniu-js'
const OSSURL = import.meta.env.VITE_OSS_PATH
const userInfo = JSON.parse(localStorage.getItem("info"))

const route = useRoute()
const router = useRoute()
const uploadStore = useSpinStore()

/**
 * 详情
 * @type {null}
 */
const detail = ref({})
const getDetail = () => {
  requestHomeWorkDetail(route.params.id).then(res => {
    detail.value = res.data
  })
}
onMounted(() => {
  getDetail()
})

/**
 * 作业文件地址
 * @type {string}
 */
let fileUrl = ''

const customRequest = ({
  file,
  data,
  headers,
  withCredentials,
  action,
  onFinish,
  onError,
  onProgress
}) => {
  upFileMethods(file.file)
};

// 上传图片、视频、附件
const upFileMethods = async (file) => {
  // type: 1 图片 2 视频 3 附件
  let token = ''
  const {data} = await getUpToken()
  token = data
  const observable = qiniu.upload(file, `study/homework/${detail.value.title}/${userInfo.data.studentNumber}/${file.name}`, token)
  observable.subscribe({
    next(res) {
      //loading开始
      uploadStore.updateLoadingFlag(1)
      console.log( '成功' , res)
    },
    error(err) {
      uploadStore.updateLoadingFlag(0)
      console.log( '错误上传附件' , err)
    },
    complete(res) {
      uploadStore.updateLoadingFlag(0)
      console.log(OSSURL + res.key, '上传成功');
      fileUrl = `${OSSURL}/${res.key}`
    }
  })
}

const submitHomework = () => {
  if (!fileUrl) {
    $message.error('清先上传文件！')
    return
  }
  //作业id
  const id = route.params.id
  requestSubmitHomework({
    id,
    url: fileUrl
  }).then(res => {
    $message.success('提交成功')
    location.reload()
  })
}

/**
 * 修改提交状态
 * @param flag
 */
const changeSubmitFlag = (flag) => {
  detail.value.submitFlag = 0
}
</script>

<template>
  <Header :page="true"></Header>
  <n-card class="card">
    <h1 class="text-3xl">{{ detail.title }}</h1>
    <p>科目：
      <n-tag type="success">
        {{ detail.typeName }}
      </n-tag>
    </p>
    <p>创建时间：{{ detail.createTime }}</p>
    <p>
      作业时间：
      <n-tag type="warning">{{ detail.startTime }} - {{ detail.endTime }}</n-tag>
    </p>
    <editor :initHtml="detail.content" :toolbar-visible="false" placeholder="请输入" :editor-height="'auto'" read-only />
  </n-card>
  <n-card class="card">
    <n-upload :disabled="detail.submitFlag == 1" :custom-request="customRequest" :max="1">
      <n-upload-dragger>
        <div style="margin-bottom: 12px">
          <n-icon size="48" :depth="3">
            <archive-icon />
          </n-icon>
        </div>
        <n-text style="font-size: 16px">
          点击或者拖动文件到该区域来上传
        </n-text>
        <n-p depth="3" style="margin: 8px 0 0 0">
          请不要上传敏感数据，比如你的银行卡号和密码，信用卡号有效期和安全码
        </n-p>
      </n-upload-dragger>
    </n-upload>
    <div style="text-align: center">
      <n-tooltip placement="top" trigger="hover" v-if="detail.submitFlag == 1">
        <template #trigger>
          <n-gradient-text type="error">
            重新提交：
          </n-gradient-text>
        </template>
        <span> 如果提交错作业了,可以在有效期内通过此选项进行覆盖提交，此功能不限次数 </span>
      </n-tooltip>
      <n-switch v-if="detail.submitFlag == 1" class="mr-4" v-model:value="active" @update:value="changeSubmitFlag" />
      <n-popconfirm @positive-click="submitHomework">
        <template #trigger>
          <n-button type="primary" v-if="detail.submitFlag == 0">提交</n-button>
          <n-button type="warning" disabled v-else="detail.submitFlag == 1">您已提交</n-button>
        </template>
        系统实时查重，请勿随意复制。
      </n-popconfirm>
    </div>
  </n-card>
</template>

<style scoped lang="less">
.card {
  p {
    margin: 16px 0;
  }
}
</style>